package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.core.xml.StubObject;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.List;


/**
 * 这个一个fragment容器
 * 动态的从配置文件中读取子孩子（子孩子也是fragment）然后添加到布局文件中
 * <p>
 * 子孩子传值及使用请移步 {@link TestFragment}
 * 配置文件如下
 * 第一层
 * <node id="fragmentContainer" caption="测试" viewType="display" AndroidShow="com.efounder.fragment.FragmentContainerFragment"/>
 *
 * 第二层
 * <fragmentContainer>
 * <node id="xinwen" caption="测试" viewType="display" AndroidShow="com.efounder.fragment.TestFragment" ></node>
 * <node id="xinwen1" caption="测试1" viewType="display" AndroidShow="com.efounder.fragment.TestFragment2" ></node>
 * <node id="xinwen2" caption="测试2" viewType="display" AndroidShow="com.efounder.fragment.TestFragment1" weight="1"></node>
 * </fragmentContainer>
 *
 * @author 梅俊
 */
@SuppressLint("NewApi")
public class FragmentContainerFragment extends BaseFragment {

    private static final String TAG = "Containerfragment";

    private LinearLayout rootView;//缓存Fragment view


    private StubObject mainMenuItem;
    private List<StubObject> childFragments;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (null != savedInstanceState) {
            List<StubObject> extEdgeMenus = (List<StubObject>) savedInstanceState
                    .getSerializable("databack");
            String titleStr = (String) savedInstanceState.getSerializable("title");
        }

        //初始化参数
        if (getArguments() != null) {
            mainMenuItem = (StubObject) getArguments().getSerializable("stubObject");
            childFragments = Registry.getRegEntryList((String) mainMenuItem.getID());
        }


        //初始化view
        if (rootView == null) {
            rootView = (LinearLayout) inflater.inflate(R.layout.fragment_container, container, false);

        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        //判断是否都配有权重
        boolean hasWeight = false;
        for (int i = 0; i < childFragments.size(); i++) {
            StubObject stubObject = childFragments.get(i);
            Hashtable stubTable = stubObject.getStubTable();
            if (stubTable.containsKey("weight")) {
                //如何任何一个子孩子使用了权重配置则不再使用scrollview包裹，（scrollview无法动态指定孩子的高度，指定了weight的孩子将不会显示）
                hasWeight = true;
                break;
            }
        }

        //如果都配有权重需要根据权重指定view高度
        if (hasWeight) {
            attachFragmenttoRoot(rootView);
        } else {
            //如果没有权重则根据自身指定的高度来适配
            //添加scrollview布局
            ScrollView scrollViewchild = new ScrollView(this.getActivity());
            scrollViewchild.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            scrollViewchild.setFillViewport(true);
            //scrollview布局添加LinearLayout
            rootView.addView(scrollViewchild);

            LinearLayout linearChild = new LinearLayout(this.getContext());

            LinearLayout.LayoutParams linearChildParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            linearChild.setLayoutParams(linearChildParams);
            scrollViewchild.addView(linearChild);
            linearChild.setOrientation(LinearLayout.VERTICAL);
            attachFragmenttoRoot(linearChild);

        }


        return rootView;

    }

    private void attachFragmenttoRoot(LinearLayout mather) {
        //直接根据子孩子的个数给根布局添加container并将fragment添加进去
        for (int i = 0; i < childFragments.size(); i++) {

            StubObject stubObject = childFragments.get(i);
            Hashtable stubTable = stubObject.getStubTable();
            Object androidShow = stubTable.get("AndroidShow");
            if (androidShow == null) {
                Log.e(TAG, "onCreateView: " + androidShow + "is null");
                continue;
            }

            FrameLayout frameLayout = new FrameLayout(this.getContext());
            frameLayout.setId(View.generateViewId());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            if (mather == rootView && stubTable.containsKey("weight")) {
                //如果是scrollview则不添加权重属性
                params.weight = Float.parseFloat(String.valueOf(stubTable.get("weight")));
            }
            frameLayout.setLayoutParams(params);
            mather.addView(frameLayout);
            Class<?> clazz = null;
            try {
                clazz = Class.forName(String.valueOf(androidShow));
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(StubObject.class);
                BaseFragment fragment = (BaseFragment) declaredConstructor.newInstance(stubObject);
//                TestFragment testFragment = new TestFragment(null);
                getChildFragmentManager().beginTransaction().add(frameLayout.getId(), fragment).commit();
            } catch (ClassNotFoundException e) {
                Log.e(TAG, "无法找到类 " + androidShow);
                e.printStackTrace();
                mather.removeView(frameLayout);
                continue;
            } catch (NoSuchMethodException e) {
                Log.e(TAG, androidShow + " 需要一个构成方法，此构造方法的参数必须指定为stubObject");
                e.printStackTrace();
                mather.removeView(frameLayout);
                continue;
            } catch (ClassCastException e) {
                Log.e(TAG, androidShow + "必须继承" + BaseFragment.class.getName());
                e.printStackTrace();
                mather.removeView(frameLayout);
                continue;

            } catch (Exception e) {
                Log.e(TAG, " 初始化" + androidShow + "异常");
                e.printStackTrace();
                mather.removeView(frameLayout);
                continue;
            }


        }
    }


}
